import React,{Component} from 'react'
import {
    Image,
    TouchableOpacity,
    View,
    Text,
    Dimensions,
    ART,
    Animated,
    TouchableWithoutFeedback,
    Vibration,
    Modal,
    DeviceEventEmitter
} from "react-native";
import PublicRelate from "./network/request/PublicRelate";
import {Toast} from "./src/baseClass/Toast";
import {isIphoneX} from "./src/baseClass/BaseScreen";

export const {width, height} = Dimensions.get('window');

const {Surface, Shape, Path} = ART;

const DEFAULT_TOGGLE_SIZE = 80;
const DEFAULT_ACTION_SIZE = 50;
const DEFAULT_TOGGLE_ANIMATION_DURATION = 300;
const DEFAULT_ACTION_STAGING_DURATION = 100;
const DEFAULT_ACTION_ANIMATION_DURATION = 200;
const DEFAULT_NAVIGATION_DELAY = 500;
const DEFAULT_EXPANDING_ANGLE = 135;

export default class PlusBarButton extends Component{

    constructor(props) {
        super(props);

        this.state = {
            isVisible:false,
            menuVisible:false,
            active:false,
            actionItems:[
                {title:'帖子',image:require('./resource/image/Public/circle-menu-post-icon.png'),routeName:'PublishPost',type:0},
                {title:'广场',image:require('./resource/image/Public/circle-menu-square-icon.png'),routeName:'PublishSquare',type:3},
                {title:'问答',image:require('./resource/image/Public/circle-menu-qa-icon.png'),routeName:'PublishQA',type:2},
                // {title:'口碑',image:require('./resource/image/Public/circle-menu-reputation-icon.png'),routeName:'PublishReputation',type:1}
                ],
            actionSize: DEFAULT_ACTION_SIZE,
            actionExpandingAngle: DEFAULT_EXPANDING_ANGLE,
            toggleSize: DEFAULT_TOGGLE_SIZE,
            navigationDelay: DEFAULT_NAVIGATION_DELAY,
            toggleAnimationDuration: DEFAULT_TOGGLE_ANIMATION_DURATION,
            actionAnimationDuration: DEFAULT_ACTION_ANIMATION_DURATION,
            actionStagingDuration: DEFAULT_ACTION_STAGING_DURATION,

            eButtonX:0,
        }

        this.activation = new Animated.Value(0);
    }

    renderActions = () => {

        const {
            actionItems,
            actionSize,
            actionExpandingAngle
        } = this.state;

        const STEP = DEFAULT_EXPANDING_ANGLE / actionItems.length;

        return actionItems.map((item,i) => {
            const offset = (STEP * (i + 1)) / actionExpandingAngle - 0.5;
            const angle = -90 + (actionExpandingAngle * offset) - (STEP / 2);
            const radius = actionSize*2;

            const x = radius * Math.cos(-angle * Math.PI / 180);
            const y = radius * Math.sin(-angle * Math.PI / 180);

            const activationScale = this[`actionActivation_${i}`].interpolate({
                inputRange: [0, 0.5, 1],
                outputRange: [0, 0, 1]
            });

            const activationPositionX = this[`actionActivation_${i}`].interpolate({
                inputRange: [0, 1],
                outputRange: [0, x]
            });

            const activationPositionY = this[`actionActivation_${i}`].interpolate({
                inputRange: [0, 1],
                outputRange: [0, y]
            });

            const AnimatedTouchable = Animated.createAnimatedComponent(TouchableOpacity);
            return (
                <Animated.View
                    key={`action_${i}`}
                    style={[Styles.actionContainer, {
                        marginLeft: actionSize*3 / 2,
                        left: activationPositionX,
                        bottom: activationPositionY,
                        transform: [
                            {scale: activationScale}
                        ]
                    }]}
                >
                    <AnimatedTouchable
                        style={[Styles.actionContent, {
                            width: actionSize,
                            height: actionSize,
                            borderRadius: actionSize / 2,
                            backgroundColor: '#EAF3F3',
                        }]}
                        onPress={() => this.actionPressed(item)}
                    >
                        <Text style={{fontSize:12}}>{item.title}</Text>
                        <Image style={{marginTop:5}} source={item.image} />
                    </AnimatedTouchable>
                </Animated.View>
            );
        })
    }

    render(): React.ReactNode {

        let yuanxing_path2 = Path()
            .moveTo(0,67)
            .arc(134, 0,67) // 给定了终点的坐标，即可自动算出半径,第三个参数 的范围预估 不可大于 真正的半径 不可小于1
            .close()


        return (
            <View style={{zIndex:999,alignItems:'center',flex:1,justifyContent:'flex-end',backgroundColor:'#00000000'}}>
                {/*{this.state.menuVisible ?*/}
                    {/*<TouchableOpacity style={{height:height,width:width,backgroundColor:'#00000000',justifyContent:'flex-end',alignItems:'center'}}*/}
                                      {/*onPress={() => this.changeMenuVisible()}*/}
                                      {/*activeOpacity={1}>*/}
                        {/*<TouchableOpacity >*/}
                        {/*<Surface width={134} height={67} style={{backgroundColor:'#00000000'}}>*/}
                            {/*<Shape d={yuanxing_path2} stroke="#EAF3F3" strokeWidth={1} fill="#EAF3F3"/>*/}
                        {/*</Surface>*/}
                        {/*</TouchableOpacity>*/}
                    {/*</TouchableOpacity>*/}
                    {/*: null*/}
                {/*}*/}

                {/*<View style={{alignItems:'center',backgroundColor:'orange'}}>*/}
                    {/*<TouchableOpacity style={{height:this.state.active ? height : 0,width:width,backgroundColor:'red',justifyContent:'flex-end',alignItems:'center'}}*/}
                                      {/*activeOpacity={1}*/}
                                      {/*onPress={() => this.changeMenuVisible()}>*/}
                    {/*</TouchableOpacity>*/}
                    {/*<View style={{position:'absolute',backgroundColor:'green',bottom:0}}>*/}
                        {/*{this.renderActions()}*/}
                    {/*</View>*/}
                {/*</View>*/}

                {/*{this.state.menuVisible ?
                    <View style={{position:'absolute',bottom: 0,alignItems:'center',height:height,elevation: 999,backgroundColor:'#00000000'}}>
                        <TouchableOpacity style={{height:this.state.active ? height : 0,width:width,backgroundColor:'#00000000',justifyContent:'flex-end',alignItems:'center'}}
                        activeOpacity={1}
                        onPress={() => this.changeMenuVisible()}>
                        </TouchableOpacity>
                        <View style={{backgroundColor:'green'}}>
                            {this.renderActions()}
                        </View>
                    </View>
                    : null
                }*/}
                <TouchableOpacity style={{zIndex:999,width:100,height:48,backgroundColor:'white',alignItems:'center'}}//white
                                  ref={(ref) => this.eButton = ref}
                                  activeOpacity={0.8}
                                  onPress={() => this.changeMenuVisible()}>
                    <View style={{marginTop:-20,width:66,height:66,borderRadius:33,backgroundColor:'white',justifyContent:'center',alignItems:'center',borderColor:'#E8E8E8',borderWidth:1}}>
                    </View>
                    <View style={{alignItems:'center',backgroundColor:'white',width:100,height:80,position:'absolute',marginTop:0}}>
                    </View>
                    <View style={{alignItems:'center',backgroundColor:'#00000000',width:100,height:80,position:'absolute',marginTop:-10}}>
                        <Image style={{marginTop:0}} source={this.state.active ? require('./resource/image/Home/tab_eadd_selcted.png') : require('./resource/image/Home/tab_eadd_normal.png')} />
                        <Text style={{marginTop:7,fontSize: 12,color:this.state.active ? 'black' : '#BDD8D8'}}>发布</Text>
                    </View>
                </TouchableOpacity>
                <Modal animationType={'none'}
                       transparent={true}
                       visible={this.state.active}
                       onRequestClose={()=>{this.changeMenuVisible()}}>
                    <TouchableOpacity activeOpacity={1} style={{backgroundColor:'#00000000',position:'absolute',bottom: 0,alignItems:'flex-start',justifyContent:'center',height:height,width:width}}
                                      onPress={()=>this.changeMenuVisible()}>
                        <View style={{position:'absolute',left:this.state.eButtonX-(200/2-100/2),backgroundColor:'#00000000',bottom:isIphoneX ? 34 : 0,height:200,width:200}}>
                            {this.renderActions()}
                        </View>
                    </TouchableOpacity>
                </Modal>
            </View>
        );
    }

    changeMenuVisible() {

        DeviceEventEmitter.emit('PauseVideo');

        this.eButton.measure((x,y,width,height,locationX,locationY) => {
            // this.state.eButtonX = locationX;

            this.setState({
                eButtonX:locationX,
            })

        })


        const {
            actionItems,
            toggleVibration,
            toggleAnimationDuration,
            actionAnimationDuration,
            actionStagingDuration,
            animateIcon
        } = this.state;

        if (this.state.active) {

            Animated.parallel([
                animateIcon && Animated.timing(this.activation, {toValue: 0, duration: toggleAnimationDuration}),
                Animated.stagger(actionStagingDuration, actionItems.map((v, i) => Animated.timing(this[`actionActivation_${(actionItems.length - 1) - i}`], {
                    toValue: 0,
                    duration: actionAnimationDuration
                })))
            ]).start();

            setTimeout(() => {
                this.setState({active: false});
            },(actionAnimationDuration+actionStagingDuration)*(actionItems.length-1)-actionStagingDuration);

        }else {
            this.setState({active: true});

            Animated.parallel([
                animateIcon && Animated.timing(this.activation, {toValue: 1, duration: toggleAnimationDuration}),
                Animated.stagger(actionStagingDuration, actionItems.map((v, i) => Animated.timing(this[`actionActivation_${i}`], {
                    toValue: 1,
                    duration: actionAnimationDuration
                })))
            ]).start();
        }

        toggleVibration && Vibration.vibrate();
    }

    makeActivations = (actionItems) => {
        actionItems.forEach((v, i) => this[`actionActivation_${i}`] = new Animated.Value(0));
        this.setState({menuVisible: true});
    };

    componentWillReceiveProps(nextProps) {
        // if (nextProps.routes !== this.props.routes) {
        //     this.makeActivations(nextProps.routes);
        // }
    }

    componentWillMount(): void {
        this.makeActivations(this.state.actionItems);
    }

    componentWillUnmount() {
        this.setState = (state, callback) => {
            return
        }
    }

    actionPressed (item) {

        let that = this;
        PublicRelate.checkPublishPermission(item.type,function (res) {
            if (res) {

                if (res.data.status === 0) {
                    Toast.show(res.data.msg);
                    return;
                }

                that.changeMenuVisible();

                const {
                    actionVibration,
                    navigationDelay
                } = that.props;

                actionVibration && Vibration.vibrate();

                if (item.routeName) {
                    setTimeout(() => that.props.navigation.navigate({
                        routeName: item.routeName,
                        params:{isAdmin:res.data.is_admin}
                    }), navigationDelay);
                }
            }
        })
    }

}

const Styles = {
    actionContainer: {
        position: 'absolute'
    },
    actionContent: {
        flex: 1,
        alignItems: 'center',
        justifyContent: 'center'
    }
}
